let _Vue
class Router {
    static install(Vue) {
        if (Router.install.installed) {
            return
        }
        // 将Vue存在在当前
        _Vue = Vue
        Vue.mixin({
            beforeCreate() {
                if (this.$options.router) {
                    Vue.prototype.$router = this.$options.router
                    this.$options.router.init()
                }
            }
        })
    }
    constructor(options) {
        this.options = options
        this.mode = options.mode || 'hash'
        this.routerMap = {}
        this.data = _Vue.observable({
            current: '/'
        })
    }
    init() {
        this.initRouterMap()
        this.initComponent(_Vue)
        this.initCurrent()
        this.initEvent()
    }
    initRouterMap() {
        this.options.routes.map(route => {
            this.routerMap[route.path] = route.component
        })
    }
    initComponent(Vue) {
        const Link = {
            name: 'RouterLink',
            props: {
                to: {
                    type: String,
                    required: true
                }
            },
            methods: {}
        }
        const View = {
            render: h => h(this.routerMap[this.data.current])
        }
        if (this.mode === 'history') {
            Link.render = function (h) {
                return h('a', {
                    attrs: {
                        href: this.to
                    },
                    on: {
                        click: this.clickHandler
                    }
                }, this.$slots.default)
            }
            Link.methods.clickHandler = function (e) {
                e.preventDefault()
                history.pushState({}, '', this.to)
                this.$router.data.current = this.to
            }
        } else {
            Link.render = function (h) {
                return h('a', {
                    attrs: {
                        href: '/#' + this.to
                    }
                }, this.$slots.default)
            }
        }
        Vue.component('router-link', Link)
        Vue.component('router-view', View)
    }
    // 第一次加载页面初始化
    initCurrent() {
        // history模式
        if (this.mode === 'history') {
            this.data.current = location.pathname
            return
        }
        // hash模式
        if (location.hash === '') {
            window.location.hash = '#/'
        }
        this.data.current = location.hash.slice(1)
    }
    initEvent() {
        // 监听hash改变
        window.addEventListener('hashchange', () => {
            this.data.current = location.hash.slice(1)
        })
        // 监听浏览器的的历史记录  当历史记录条目更改时，将触发popstate事件
        window.addEventListener('popstate', () => {
            this.data.current = location.pathname
        })
    }
}
export default Router